package devbureau.fstore.common.translate.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import devbureau.fstore.common.TranslatorItem;
import devbureau.fstore.common.translate.FileParser;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

public class CSVFileParser implements FileParser {
	
	static Logger logger = Logger.getLogger(CSVFileParser.class);

	private List<TranslatorItem> items = null;
	// TODO: Make more complex expression
	private static final String SPLIT_REGEXP = ";";

	@Override
	public List<TranslatorItem> parse(byte[] fileData) throws Exception {
		logger.debug("#parse enter");
		init();
		StringBuffer errors = new StringBuffer();
		try{
            ByteArrayInputStream bais = new ByteArrayInputStream(fileData);
			BufferedReader br = new BufferedReader(new InputStreamReader(bais));
			String line = null;
			int number = 0;
			while((line = br.readLine()) != null){
					try{
                        logger.debug("#parse line = " + line);
						items.add(parseLine(line));
					}catch(Exception ex){
						errors.append("\nВ строке " + number + " ошибка : " + ex.getMessage() );	
					}
				number++;
			}
		}catch(IOException ex){
			logger.error(ex,ex);
			throw new Exception("\nОшибка чтения данных.\n Ошибка : '"+ex.getMessage()+"'.");
		}
		
		if(errors.length()>0) {
			throw new Exception("\nОшибка разбора данных.\n Ошибки : " + errors.toString());
		}
		logger.debug("#parse exit");
		return items;
	}

	private void init() {
		items = new ArrayList<TranslatorItem>();
	}

	TranslatorItem parseLine(String line) throws Exception {
		logger.trace("#parseLine enter");
		
		TranslatorItem item = null;
		
    	String[] data = line.split(SPLIT_REGEXP);
        item =HelperFileParser.parseData(data);
		
		logger.trace("#parseLine exit");
		return item;
	}


}
